# -*- coding: utf-8 -*-
# This code written by ChanGOGOGO
""" """
import uvicorn
import logging
from typing import Any
from fastapi import FastAPI, Body
from datetime import datetime
from util import (
    data2beautify,
    create_uuid1,
    random_str,
    setup_logging,
    calc_time_interval,
    get_now_time,
)


app = FastAPI()
# （通用）通话记录回调信息
session_callback_info = {}
# （蚂蚁）通话记录回调信息
ant_callback_info = {}
# 凯森意向回调信息
kaisen_callback_info = {}


@app.post("/sessionCallback")
async def session_callback(body: Any = Body(...)):
    """
    一个工具函数，用于日志记录和响应
    :param body: 请求体
    :return: {'code': 0, 'message': 'OK', 'data': {}}  # 响应体
    """
    global session_callback_info
    now_time = get_now_time()
    # 记录接收回调时间
    # phone = body.get("data").get("sessionInfo").get("telNum")
    # callout_dial_time = body.get("data").get("sessionInfo").get("calloutDialTime")
    # callout_finish_time = body.get("data").get("sessionInfo").get("calloutFinishTime")
    # with open("./txt/callback.csv", "a", encoding="utf-8") as file:
    #     file.writelines(
    #         f"{phone},{callout_dial_time},{callout_finish_time},{now_time}\n"
    #     )
    # 上一次回调时间，上一次回调次数初始值
    last_session_callback_time = ""
    current_session_callback_count = 1
    table_prefix = body.get("data").get("tablePrefix")  # 表前缀
    table_suffix = body.get("data").get("tableSuffix")  # 表后缀
    if table_suffix.startswith("_in"):
        call_type = "呼入"
    else:
        call_type = "呼出"
    task_id = body.get("data").get("sessionInfo").get("innerTaskId")
    session_id = body.get("data").get("sessionInfo").get("sessionId")
    case_id = body.get("data").get("sessionInfo").get("caseId")
    find_table_prefix = session_callback_info.get(table_prefix)
    # 如果存在该表前缀，则继续判断表后缀
    if find_table_prefix:
        find_table_suffix = session_callback_info.get(table_prefix, {}).get(
            table_suffix
        )
        if find_table_suffix:
            find_task_id = (
                session_callback_info.get(table_prefix, {})
                .get(table_suffix, {})
                .get(task_id)
            )
            if find_task_id:
                case_ids = (
                    session_callback_info.get(table_prefix, {})
                    .get(table_suffix, {})
                    .get(task_id, {})
                    .get("case_ids")
                )
                if case_id not in case_ids:
                    case_ids.append(case_id)
                find_session_id = (
                    session_callback_info.get(table_prefix, {})
                    .get(table_suffix, {})
                    .get(task_id, {})
                    .get(session_id)
                )
                if find_session_id:
                    last_session_callback_time = (
                        session_callback_info.get(table_prefix, {})
                        .get(table_suffix, {})
                        .get(task_id, {})
                        .get(session_id, {})
                        .get("last_session_callback_time")
                    )
                    current_session_callback_count = (
                        session_callback_info.get(table_prefix, {})
                        .get(table_suffix, {})
                        .get(task_id, {})
                        .get(session_id, {})
                        .get("current_session_callback_count")
                    )
                    session_callback_info[table_prefix][table_suffix][task_id][
                        session_id
                    ] = {
                        "last_session_callback_time": now_time,
                        "current_session_callback_count": current_session_callback_count
                        + 1,
                    }
                else:
                    session_callback_info[table_prefix][table_suffix][task_id][
                        session_id
                    ] = {
                        "last_session_callback_time": now_time,
                        "current_session_callback_count": current_session_callback_count
                        + 1,
                    }
                session_callback_info[table_prefix][table_suffix][task_id][
                    "task_callback_count"
                ] += 1
            else:
                session_callback_info[table_prefix][table_suffix][task_id] = {
                    session_id: {
                        "last_session_callback_time": now_time,
                        "current_session_callback_count": current_session_callback_count
                        + 1,
                    },
                    "case_ids": [case_id],
                    "task_callback_count": 1,
                }
        else:
            session_callback_info[table_prefix][table_suffix] = {
                task_id: {
                    session_id: {
                        "last_session_callback_time": now_time,
                        "current_session_callback_count": current_session_callback_count
                        + 1,
                    },
                    "case_ids": [case_id],
                    "task_callback_count": 1,
                }
            }
    else:
        session_callback_info[table_prefix] = {
            table_suffix: {
                task_id: {
                    session_id: {
                        "last_session_callback_time": now_time,
                        "current_session_callback_count": current_session_callback_count
                        + 1,
                    },
                    "case_ids": [case_id],
                    "task_callback_count": 1,
                }
            }
        }
    time_interval = calc_time_interval(last_session_callback_time, now_time)
    # 获取任务下回调名单数量（case_id去重）
    task_callback_list_count = len(
        session_callback_info.get(table_prefix, {})
        .get(table_suffix, {})
        .get(task_id, {})
        .get("case_ids")
    )
    # 获取任务下通话回调总数
    task_callback_count = (
        session_callback_info.get(table_prefix, {})
        .get(table_suffix, {})
        .get(task_id, {})
        .get("task_callback_count")
    )
    logging.info(
        f"收到'{call_type}'sessionID为{session_id}的通话的第{current_session_callback_count}次通话回调(所属任务{task_id}，回调名单数:{task_callback_list_count}，回调总数：{task_callback_count})，距离上次回调间隔{time_interval}：\n{data2beautify(body)}"
    )
    code = 0  # 0-成功，1-失败
    if code == 1:
        message = "UNKNOWN"
    else:
        message = "OK"
    res = {"code": code, "message": message, "data": {}}
    logging.info(
        f"针对'{call_type}'sessionID为{session_id}的通话的第{current_session_callback_count}次通话回调(所属任务{task_id}，回调名单数:{task_callback_list_count}，回调总数：{task_callback_count})，给予响应：\n{data2beautify(res)}"
    )
    return res


@app.post("/taskCallback")
def task_callback(body: Any = Body(...)):
    logging.info(f"任务状态回调接口收到请求：\n{data2beautify(body)}")
    res = {"code": 0, "message": "OK", "data": {}}
    logging.info(f"任务状态回调接口响应：\n{data2beautify(res)}")
    return res


@app.post("/mock")
def mock(body: Any = Body(...)):
    logging.info(f"mock接口收到请求：\n{data2beautify(body)}")
    res = {"code": 0, "message": "OK", "data": {}}
    logging.info(f"mock接口响应：\n{data2beautify(res)}")
    return res


@app.post("/mock_ant")
def mock_ant(body: Any = Body(...)):
    global ant_callback_info
    now_time = get_now_time()
    product_id = body.get("productInstanceId")
    last_ant_callback_time = ""
    current_ant_callback_count = 1
    call_id = body.get("callId")
    find_call_id = ant_callback_info.get(call_id)
    if find_call_id:
        last_ant_callback_time = ant_callback_info.get(call_id, {}).get(
            "last_ant_callback_time"
        )
        current_ant_callback_count = ant_callback_info.get(call_id, {}).get(
            "current_ant_callback_count"
        )
    ant_callback_info[call_id] = {
        "last_ant_callback_time": now_time,
        "current_ant_callback_count": current_ant_callback_count + 1,
    }
    time_interval = calc_time_interval(last_ant_callback_time, now_time)
    logging.info(
        f"🐜 收到蚂蚁{product_id}环境通话 {call_id} 第{current_ant_callback_count}次回调，距离上一次回调间隔{time_interval}：\n{data2beautify(body)}"
    )
    result_code = "OK"  # OK、UNKNOWN
    if result_code == "OK":
        result_msg = "成功"
    else:
        result_msg = "失败"
    res = {
        "reqMsgId": create_uuid1(),
        "resultCode": result_code,
        "resultMsg": result_msg,
    }
    logging.info(
        f"🐜 针对蚂蚁{product_id}环境通话 {call_id} 第{current_ant_callback_count}次回调，给予响应：\n{data2beautify(res)}"
    )
    return res


@app.post("/transferToLabor")
def transfer_to_labor(body: Any = Body(...)):
    """凯森转人工通知mock"""
    logging.info(f"/transferredToLabor接口收到请求：\n{data2beautify(body)}")
    code = 0  # 0-成功，1-失败
    message = ""
    agentstate = 0  # 坐席状态：0-空闲，1-繁忙
    data = {"agentstate": agentstate}
    res = {"code": code, "message": message, "data": data}
    logging.info(f"/transferredToLabor给与响应：\n{data2beautify(res)}")
    return res


@app.post("/kaisen_intent_notify")
def kaisen_intent_notify(body: Any = Body(...)):
    """凯森客户意向通知"""
    global kaisen_callback_info
    now_time = get_now_time()
    out_session_id = body.get("outSessionId")
    find_out_session_id = kaisen_callback_info.get(out_session_id)
    last_kaisen_callback_time = ""
    current_kaisen_callback_count = 1
    if find_out_session_id:
        last_kaisen_callback_time = kaisen_callback_info.get(out_session_id, {}).get(
            "last_kaisen_callback_time"
        )
        current_kaisen_callback_count = kaisen_callback_info.get(
            out_session_id, {}
        ).get("current_kaisen_callback_count")
    kaisen_callback_info[out_session_id] = {
        "last_kaisen_callback_time": now_time,
        "current_kaisen_callback_count": current_kaisen_callback_count + 1,
    }
    time_interval = calc_time_interval(last_kaisen_callback_time, now_time)
    logging.info(
        f"接收到凯森通话意向 {out_session_id} 的第{current_kaisen_callback_count}次回调，距离上次回调间隔{time_interval}：\n{data2beautify(body)}"
    )
    code = 0  # 0-成功，1-失败
    if code == 1:
        message = "失败"
    else:
        message = ""
    res = {"code": code, "message": message}
    logging.info(
        f"给予凯森通话意向 {out_session_id} 的第{current_kaisen_callback_count}次回调响应：\n{data2beautify(res)}"
    )
    return res


@app.post("/dialogs/turn/callback")
def ec_turn_callback(body: Any = Body(...)):
    logging.info(f"EC轮次回调接口收到请求：\n{data2beautify(body)}")
    res = {"code": 0, "message": "OK"}
    logging.info(f"EC轮次回调接口给予响应：\n{data2beautify(res)}")
    return res


@app.post("/dialogs/finish/callback")
def ec_finish_callback(body: Any = Body(...)):
    logging.info(f"EC通话结束回调接口收到请求：\n{data2beautify(body)}")
    res = {"code": 0, "message": "OK"}
    logging.info(f"EC通话结束回调接口给予响应：\n{data2beautify(res)}")
    return res


@app.post("/sms_a")
def sms_a(body: Any = Body(...)):
    """蘑菇云短信mock"""
    logging.info(f"短信通道【a】接口收到请求：\n{data2beautify(body)}")
    timestamp = int(body.get("timestamp")) / 1000
    dt_object = datetime.fromtimestamp(timestamp)
    now_time = dt_object.strftime("%Y-%m-%d %H:%M:%S")
    extend = body.get("extend")
    phones = body.get("phone")
    phone_list = phones.split(",")
    session_id = body.get("uid")
    results = list()
    uid = random_str(32)
    with open("./txt/a.txt", "a") as f:
        for phone in phone_list:
            result = {"status": "00000", "phone": phone, "desc": "提交成功"}
            results.append(result)
            f.writelines(f"{now_time},{uid},{phone},{extend},{session_id}\n")
    res = {"code": "00000", "desc": "提交成功", "uid": uid, "result": results}
    logging.info(f"短信通道【a】接口给出响应：\n{data2beautify(res)}")
    return res


@app.post("/sms_b")
def sms_b(body: Any = Body(...)):
    """蘑菇云短信mock"""
    logging.info(f"短信通道【b】接口收到请求：\n{data2beautify(body)}")
    timestamp = int(body.get("timestamp")) / 1000
    dt_object = datetime.fromtimestamp(timestamp)
    now_time = dt_object.strftime("%Y-%m-%d %H:%M:%S")
    extend = body.get("extend")
    phones = body.get("phone")
    phone_list = phones.split(",")
    session_id = body.get("uid")
    results = list()
    uid = random_str(32)
    with open("./txt/b.txt", "a") as f:
        for phone in phone_list:
            result = {"status": "00000", "phone": phone, "desc": "提交成功"}
            results.append(result)
            f.writelines(f"{now_time},{uid},{phone},{extend},{session_id}\n")
    res = {"code": "00000", "desc": "提交成功", "uid": uid, "result": results}
    logging.info(f"短信通道【b】接口给出响应：\n{data2beautify(res)}")
    return res


@app.post("/sms_c")
def sms_c(body: Any = Body(...)):
    """蘑菇云短信mock"""
    logging.info(f"短信通道【c】接口收到请求：\n{data2beautify(body)}")
    timestamp = int(body.get("timestamp")) / 1000
    dt_object = datetime.fromtimestamp(timestamp)
    now_time = dt_object.strftime("%Y-%m-%d %H:%M:%S")
    extend = body.get("extend")
    phones = body.get("phone")
    phone_list = phones.split(",")
    session_id = body.get("uid")
    results = list()
    uid = random_str(32)
    with open("./txt/c.txt", "a") as f:
        for phone in phone_list:
            result = {"status": "00000", "phone": phone, "desc": "提交成功"}
            results.append(result)
            f.write(f"{now_time},{uid},{phone},{extend},{session_id}\n")
    res = {"code": "00000", "desc": "提交成功", "uid": uid, "result": results}
    logging.info(f"短信通道【c】接口给出响应：\n{data2beautify(res)}")
    return res


@app.post("/sms_d")
def sms_d(body: Any = Body(...)):
    """蘑菇云短信mock"""
    logging.info(f"短信通道【d】接口收到请求：\n{data2beautify(body)}")
    timestamp = int(body.get("timestamp")) / 1000
    dt_object = datetime.fromtimestamp(timestamp)
    now_time = dt_object.strftime("%Y-%m-%d %H:%M:%S")
    extend = body.get("extend")
    phones = body.get("phone")
    phone_list = phones.split(",")
    session_id = body.get("uid")
    results = list()
    uid = random_str(32)
    with open("./txt/d.txt", "a") as f:
        for phone in phone_list:
            result = {"status": "00000", "phone": phone, "desc": "提交成功"}
            results.append(result)
            f.writelines(f"{now_time},{uid},{phone},{extend},{session_id}\n")
    res = {"code": "00000", "desc": "提交成功", "uid": uid, "result": results}
    logging.info(f"短信通道【d】接口给出响应：\n{data2beautify(res)}")
    return res


@app.post("/callback")
def callback(body: Any = Body(...)):
    logging.info(f"回调接口/callback收到请求：\n{data2beautify(body)}")
    res = {"code": 0, "message": "成功"}
    # res = {"code": 0, "message": "OK", "data": {}}
    logging.info(f"回调接口/callback响应：\n{data2beautify(res)}")
    return res


if __name__ == "__main__":
    uvicorn.run(app="api_service:app", host="0.0.0.0", port=9999, reload=False)
